﻿using System;
using System.Collections.Specialized;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using System.Web.Profile;
using System.Web.Routing;
using Vit.Common.Helpers;
using Vit.Common.Extensions;
using Vit.Web.Models;

namespace Vit.Web.Helpers
{
    public static class URLHelper
    {
        public static string SitePath(string url)
        {
            return SitePath(url, false, false, false);
        }

        public static string SitePath(string url, bool replaceWithUserProfile, bool replaceWithRouteData, bool replaceWithQueryString)
        {
            WebSite site = ((Vit.Web.VitApplication)HttpContext.Current.ApplicationInstance).CurrentSite;
            url = url.Replace("{Site}/", site.RootPath);
            if (replaceWithUserProfile)
                url = ReplaceWithUserProfile(url);
            if (replaceWithRouteData)
                url = ReplaceWithRouteData(url);
            if (replaceWithQueryString)
                url = ReplaceWithQueryString(url);

            if (url.StartsWith("~"))
                url = url.TrimStart('~');

            return url;
        }

        public static string ReplaceWithUserProfile(string url)
        {
            Dictionary<string, string> replacements = new Dictionary<string, string>();
            var identity = MembershipHelper.GetCurrentUserIdentity();
            Dictionary<string, object> profiles = MembershipHelper.GetUserProfileProperties(identity);
            foreach (KeyValuePair<string, object> kvp in profiles)
                replacements.Add(string.Format("{{{0}}}", kvp.Key), kvp.Value.ToString());

            string replacedUrl = url.Replace(replacements);
            return replacedUrl;
        }

        public static string ReplaceWithRouteData(string url)
        {
            HttpContextBase context = new HttpContextWrapper(HttpContext.Current);
            RouteData routeData = RouteTable.Routes.GetRouteData(context);
            Dictionary<string, string> replacements = new Dictionary<string, string>();
            foreach (var kvp in routeData.Values)
                replacements.Add(string.Format("{{{0}}}", kvp.Key), kvp.Value.ToString());

            string replacedUrl = url.Replace(replacements);
            return replacedUrl;
        }

        public static string ReplaceWithQueryString(string url)
        {
            Dictionary<string, string> replacements = new Dictionary<string, string>();
            NameValueCollection nv = HttpContext.Current.Request.QueryString;
            foreach(string key in nv.Keys)
                replacements.Add(string.Format("{{{0}}}", key), nv[key]);

            string replacedUrl = url.Replace(replacements);
            return replacedUrl;
        }
    }
}
